/*
 * Proto Streamer
 * Copyright (C) 2010 John Pritchard.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */
package p.s;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * 
 */
public final class Resources 
    extends java.util.HashMap<String,Resources.Content>
{

    public final static class Content
        extends Object
    {

        public final byte[] bits;

        public Content(byte[] bits){
            super();
            this.bits = bits;
        }
    }

    private final static Resources Map = new Resources();


    public final static byte[] For(String path){

        return Map.getResource(path);
    }


    private Resources(){
        super();
    }

    public byte[] getResource(String path){

        Content content = this.get(path);
        if (null != content){

            return content.bits;
        }
        else {
            try {
                InputStream resource = this.getClass().getResourceAsStream(path);
                if (null != resource){
                    try {
                        ByteArrayOutputStream buf = new ByteArrayOutputStream();
                        {
                            byte[] iob = new byte[512];
                            int read;
                            while (0 < (read = resource.read(iob,0,512))){
                                buf.write(iob,0,read);
                            }
                        }
                        content = new Content( buf.toByteArray());
                        this.put(path,content);
                        return content.bits;
                    }
                    finally {
                        resource.close();
                    }
                }
            }
            catch (Exception any){
            }
            return null;
        }
    }
}
